import maya.cmds as cmds
import maya.mel as mel
import os, sys
import maya.OpenMaya as om
#import studio.maya.baseTools.checkInstance   as checkInstance

import core
reload(core)

def getThreshold():
    threshold = 0.0001
    return threshold

def checkInstanceObjects():
    instances = []
    iterDag = om.MItDag(om.MItDag.kBreadthFirst)
    while not iterDag.isDone():
        instanced = om.MItDag.isInstanced(iterDag)
        if instanced:
            instances.append(iterDag.fullPathName())
            
        iterDag.next()
    return instances

'''higeo'''
def deleteHistory(assetRoot, *args, **kw):
    cmds.delete(assetRoot, ch = 1)
    allProxy = cmds.ls(type = 'mentalraySubdivApprox')
    if allProxy:
        cmds.delete(allProxy)
    return core.checkResult(allowPublish=True, msg="Everything is OK")
    
def checkInstanceModel(assetRoot, *args, **kw):
    instances = checkInstanceObjects()
    if not instances:
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else:
        return core.checkResult(allowPublish=False, msg="These geometries are instances", nodes=instances)
    
def checkInvalidModel(assetRoot, *args, **kw):
    invalidMdl = cmds.ls(assetRoot, dag = 1, type = ['subdiv'])
    if not invalidMdl:
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else:
        return core.checkResult(allowPublish=False, msg="These geometries are not polygons", nodes=invalidMdl)
    
def checkInvalidObjTransform(assetRoot, *args, **kw):
    meshes      = cmds.ls(assetRoot, dag = 1, l = 1, type = ['mesh'])
    invalidTran = []
    attrs       = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
    values      = [0, 0, 0, 0, 0, 0, 1, 1, 1]
    for mesh in meshes:
        part = mesh.split('|')
        if part[-1] == 'r_eye_MIDShape' or part[-1] == 'l_eye_MIDShape':
            continue
        
        tran    = '|'.join(part[:-1])
        for i in range(0, len(attrs)):
            if not cmds.getAttr(tran + '.' + attrs[i]) == values[i]:
                invalidTran.append(tran.split('|')[-1])
                break
            
    invalidTran = list(set(invalidTran))
    if not invalidTran:
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else:
        return core.checkResult(allowPublish=False, msg="Invalid transform appear in these geometries", nodes=invalidTran)
        
def checkSameObjectInSameSpace(assetRoot, *args, **kw):
    threshold   = getThreshold()
    
    meshs       = cmds.ls(assetRoot, dag = 1, type = 'mesh')
    invalidMesh = []
    for m in meshs:
        shellNum    = cmds.polyEvaluate(m, shell = 1)
        if shellNum <= 1:
            continue
        
        resNum      = shellNum
        
        sameFaceNumMeshDict = {}
        alCheckMesh = [] 
        while resNum:
            cmds.select( (m + '.f[:]'), r = 1 )
            if alCheckMesh:
                cmds.select( alCheckMesh, d = 1 )
            
            curSel = cmds.ls(sl = 1)
            firStr = curSel[0].split('[')[1].split(']')[0].split(':')[0]      
            cmds.select( (m + '.f[' + firStr + ']'), r = 1 )
            
            ''''''''''''
            oldSel = cmds.ls(sl = 1)
            newSel = ''
            while not oldSel == newSel:
                oldSel = cmds.ls(sl = 1)
                mel.eval('PolySelectTraverse 1')
                newSel = cmds.ls(sl = 1)
                
            curSel = cmds.ls(sl = 1)
            alCheckMesh += curSel
            selFaceNum = 0
            for cs in curSel:
                firNum  = int( cs.split('[')[1].split(']')[0].split(':')[0] ) 
                lastNum = int( cs.split('[')[1].split(']')[0].split(':')[-1] )
                
                selFaceNum += (lastNum - firNum + 1)
            
            if sameFaceNumMeshDict.has_key(selFaceNum):
                oriTem = sameFaceNumMeshDict[selFaceNum]
                oriTem.append( cmds.ls(sl = 1) )
                sameFaceNumMeshDict[selFaceNum] = oriTem
            else:
                sameFaceNumMeshDict[selFaceNum] = [cmds.ls(sl = 1)]
        
            resNum -= 1
            
        for faceNum in sameFaceNumMeshDict.keys():
            faceAll = sameFaceNumMeshDict[faceNum]
            if len(faceAll) < 2:
                continue
            
            faceAllNum  = len(faceAll)
            faceBvDict  = {}
            
            initFaceGrp = [[]]
            for i in range(0, faceAllNum):
                bbox = cmds.exactWorldBoundingBox(faceAll[i])
                
                faceAllStr = ' '.join(faceAll[i])
                faceBvDict[faceAllStr] = bbox
            
                initFaceGrp[0].append(faceAllStr)
            
            for i in range(0, 6):
                sameBbTemDict = {}
                
                for j in range( 0, len(initFaceGrp) ):
                    skipNum = []                
                    loopANum = len(initFaceGrp[j])
                    print initFaceGrp[j]
                    while loopANum:
                        loopBNum = loopANum - 1
                        if skipNum.__contains__(loopANum):
                            pass
                        else:
                            while loopBNum:
                                val = float( faceBvDict[initFaceGrp[j][loopANum - 1]][i] - faceBvDict[initFaceGrp[j][loopBNum - 1]][i] )
                                if abs(val) < threshold:
                                    if sameBbTemDict.has_key(initFaceGrp[j][loopANum - 1]):
                                        oriTem = sameBbTemDict[initFaceGrp[j][loopANum - 1]]
                                        print initFaceGrp[j][loopBNum - 1]
                                        oriTem.append( initFaceGrp[j][loopBNum - 1] )
                                        sameBbTemDict[initFaceGrp[j][loopANum - 1]] = oriTem                                        
                                    else:
                                        print initFaceGrp[j][loopBNum - 1]    
                                        sameBbTemDict[initFaceGrp[j][loopANum - 1]] = [initFaceGrp[j][loopBNum - 1]]
                                        
                                    skipNum.append(loopBNum)
                                    
                                loopBNum -= 1
                        loopANum -= 1
                
                initFaceGrp = []
                sameKeys    = sameBbTemDict.keys()
                for i in range(0, len(sameKeys)):
                    sameKey = sameKeys[i]
                    initFaceGrp.append([])
                    
                    sameVal = sameBbTemDict[sameKey]
                    sameVal.append(sameKey)
                    
                    initFaceGrp[i] += sameVal
                
            if initFaceGrp:
                invalidMesh.append(m)
                break
    
    cmds.select(assetRoot, r = 1)
    if not invalidMesh:
        return core.checkResult(allowPublish=True, msg="Everything is OK")
    else:
        return core.checkResult(allowPublish=False, msg="These geometries contains overlapping polygons", nodes=invalidMesh)